﻿using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace Adnc.Application.Shared.WeChat
{
    public class WeChatService
    {
        private readonly AccessToken _token;

        private readonly WeChatOption _option;
        public WeChatService(AccessToken token
            , IOptions<WeChatOption> option)
        {
            _token = token;
            _option = option.Value;
        }

        /// <summary>
        /// 获取公众号登录信息
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        public async Task<SnsOAuth2AccessTokenResponse> GetOAuth2AccessToken(string Code)
        {
            var client = WeChatApiHttpClientFactory.CreateWeXinClient(_option);
            var request = new SnsOAuth2AccessTokenRequest() { Code = Code };
            return await client.ExecuteSnsOAuth2AccessTokenAsync(request);
        }

        /// <summary>
        /// 获取小程序登录信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<SnsJsCode2SessionResponse> GetJsCode2Session(string Code)
        {
            var client = WeChatApiHttpClientFactory.CreateWxOpenClient(_option);
            var request = new SnsJsCode2SessionRequest() { JsCode = Code };
            return await client.ExecuteSnsJsCode2SessionAsync(request);
        }

        /// <summary>
        /// 获取小程序码
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task<WxaGetWxaCodeUnlimitResponse> GetQrCode(string scene, string page)
        {
            var accessToken = await _token.GetWxOpenAccessToken();
            var client = WeChatApiHttpClientFactory.CreateWxOpenClient(_option);
            var request = new WxaGetWxaCodeUnlimitRequest
            {
                AccessToken = accessToken,
                Scene = scene,
                PagePath = page,
                IsHyaline = true
            };
            var response = await client.ExecuteWxaGetWxaCodeUnlimitAsync(request);
            if (response.ErrorCode == 40001)
            {
                accessToken = await _token.RefreshWxOpenAccessToken();
                request = new WxaGetWxaCodeUnlimitRequest
                {
                    AccessToken = accessToken,
                    Scene = scene,
                    PagePath = page,
                    IsHyaline = true
                };
                return await client.ExecuteWxaGetWxaCodeUnlimitAsync(request);
            }
            else
                return response;
        }

        /// <summary>
        /// 公众号发送消息
        /// </summary>
        /// <param name="UserOpenId"></param>
        /// <param name="TemplateId"></param>
        /// <param name="PagePath"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public async Task<CgibinMessageTemplateSendResponse> ExecuteCgibinMessageTemplateSendAsync(string UserOpenId, string TemplateId,string PagePath, object Data)
        {
            var client = WeChatApiHttpClientFactory.CreateWeXinClient(_option);
            var accessToken = await _token.GetWeXinAccessToken();
            string jsonData = JsonSerializer.Serialize(Data);
            var newdata = JsonSerializer.Deserialize<Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>>(jsonData);
            var request = new CgibinMessageTemplateSendRequest
            {
                AccessToken = accessToken,
                MiniProgram = new CgibinMessageTemplateSendRequest.Types.MiniProgram() { AppId = _option.WxOpenAppId, PagePath = PagePath },
                TemplateId = TemplateId,
                Data = newdata,
                ToUserOpenId = UserOpenId,
            };
            return await client.ExecuteCgibinMessageTemplateSendAsync(request);
        }
    }
}
